using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Auditing;
using Abp.Authorization;
using Abp.AutoMapper;
using Vecen.BangChuang.Authorization.Users;
using Vecen.BangChuang.BangChuang;
using Vecen.BangChuang.BangChuang.Areas;
using Vecen.BangChuang.BangChuang.Areas.DomainDtos;
using Vecen.BangChuang.BangChuang.Areas.Dtos;
using Vecen.BangChuang.BangChuang.DomainServices.Agents;
using Vecen.BangChuang.Sessions.Dto;
using Vecen.BangChuang.SignalR;

namespace Vecen.BangChuang.Sessions {
    /// <summary>
    /// 
    /// </summary>
    public class SessionAppService: BangChuangAppServiceBase, ISessionAppService {
        private readonly AgentDomainService _agentDomainService;
        private readonly CityDomainService _cityDomainService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="agentDomainService"></param>
        /// <param name="cityDomainService"></param>
        public SessionAppService(AgentDomainService agentDomainService, CityDomainService cityDomainService) {
            _agentDomainService = agentDomainService;
            _cityDomainService = cityDomainService;
        }

        /// <summary>
        /// 获得当前登录信息
        /// </summary>
        /// <returns></returns>
        [DisableAuditing]
        public async Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations() {

            return await GetCurrentLoginInformationAsync();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private async Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformationAsync() {
            var output = new GetCurrentLoginInformationsOutput {
                Application = new ApplicationInfoDto {
                    Version = AppVersionHelper.Version, ReleaseDate = AppVersionHelper.ReleaseDate,
                    Features = new Dictionary<string, bool> {{"SignalR", SignalRFeature.IsAvailable}}
                }
            };

            if(AbpSession.TenantId.HasValue) {
                output.Tenant = (await GetCurrentTenantAsync()).MapTo<TenantLoginInfoDto>();
            }

            if(AbpSession.UserId.HasValue) {
                var user = await GetCurrentUserAsync();
                output.User = user.MapTo<UserLoginInfoDto>();
                if(output.User != null) {
                    output.User.AvatarId =
                        await AttachmentManager.GetIdAsync(User.UserAvatarAttachmentType, output.User.Id);
                    output.User.UserType = await _agentDomainService.GetUserTypeAsync(output.User.Id);
                    output.User.HasPromotionToAgent = await _agentDomainService.GetApplyByUserIdAsync(output.User.Id)
                                                      != null;
                    output.User.AreaInfo = user.AreaCode.HasValue
                        ? await _cityDomainService.GetFullAreaNameByIdAsync(user.AreaCode.Value) : "";
                    output.User.CityInfo = (await _cityDomainService.GetFullAddressByCityId(user.AreaCode ?? 0))
                        .MapTo<FullCityOutDto>();
                    //当前用户的代理商信息
                    var usersAgent = await _agentDomainService.GetUserAgentByUserIdAsync(output.User.Id);
                    if(usersAgent != null) {
                        output.User.AgentId = usersAgent.Id;
                        var agentUser = await UserManager.GetUserByIdAsync(usersAgent.UserId);
                        output.User.AgentName = agentUser?.Name;
                        output.User.AgentPhoneNumber = agentUser?.PhoneNumber;
                    }
                    //代理商详情
                    if(output.User.UserType == UserType.FirstAgentUser
                       || output.User.UserType == UserType.SecondAgentUser) {
                        output.Agent = new AgentLoginInfo();
                        var agent = await _agentDomainService.GetByUserIdAsync(output.User.Id);
                        if(agent != null) {
                            output.Agent.Area = await _cityDomainService.GetFullAreaNameByIdAsync(agent.AreaCode);
                            output.Agent.CollegeName = agent.CollegeName;
                            output.Agent.UniversityName = agent.UniversityName;
                            var parent = await _agentDomainService.GetParentAgentByIdAsync(agent.Id);
                            if(parent != null) {
                                var superior = await UserManager.GetUserByIdAsync(parent.UserId);
                                output.Agent.Superior = superior.Name;
                                output.Agent.SuperiorPhoneNumber = superior.PhoneNumber;
                            }
                        }
                    }
                }
            }
            return output;
        }


        /// <summary>
        /// 获取当前登录信息(APP)
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformationsForApp() {
            return await GetCurrentLoginInformationAsync();
        }
    }
}